import { createRouter, createWebHistory } from 'vue-router'
import AppLayout from '../components/layout/AppLayout.vue'
import UserManagement from '../views/UserManagement.vue'
import ProductManagement from '../views/ProductManagement.vue'
import OrderManagement from '../views/OrderManagement.vue'
import CommentManagement from '../views/CommentManagement.vue'
import CustomerService from '../views/CustomerService.vue'
import SeckillProductManagement from '../views/SeckillProductManagement.vue'
import SeckillOrderManagement from '../views/SeckillOrderManagement.vue'
import Login from '@/views/Login.vue'
import { useUserStore } from '@/stores/user'
import Charts from '../views/Echarts/Charts.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        title: '登录'
      }
    },
    {
      path: '/',
      component: AppLayout,
      children: [
        {
          path: 'users',
          name: 'users',
          component: UserManagement
        },
        {
          path: 'products',
          name: 'products',
          component: ProductManagement
        },
        {
          path: 'orders',
          name: 'orders',
          component: OrderManagement
        },
        {
          path: 'comments',
          name: 'comments',
          component: CommentManagement
        },
        {
          path: 'charts',
          name: 'charts',
          component: Charts
        },
        {
          path: 'customer-service',
          name: 'customer-service',
          component: CustomerService,
          meta: {
            title: '在线客服'
          }
        },
        {
          path: 'seckill-products',
          name: 'seckill-products',
          component: SeckillProductManagement,
          meta: {
            title: '秒杀商品管理'
          }
        },
        {
          path: 'seckill-orders',
          name: 'seckill-orders',
          component: SeckillOrderManagement,
          meta: {
            title: '秒杀订单管理'
          }
        },
        {
          path: '',
          redirect: '/users' // 默认重定向到用户管理页面
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if (to.path !== '/login' && userStore.isLogin === 0) {
    next('/login')
  } else {
    next()
  }
})

export default router
